package com.groupfive.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.groupfive.common.Result;
import com.groupfive.feign.client.DeptClient;
import com.groupfive.pojo.Account;
import com.groupfive.pojo.Dept;
import com.groupfive.pojo.Employee;
import com.groupfive.service.EmployeeService;
import com.groupfive.utils.JwtUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptClient deptClient;
    @Value("${token.timeout}")
    private Integer timeout;

    /**
     * 添加
     */
    @PostMapping("/add")
    public Result add(@RequestBody Employee employee) {
        int count = employeeService.add(employee);
        if (count == 0) {
            return Result.error();
        }
        return Result.success();
    }

    /**
     * 更新数据
     */
    @PutMapping("/update")
    public Result update(@RequestBody Employee employee) {
        int count = employeeService.update(employee);
        if (count == 0) {
            return Result.error();
        }
        return Result.success();
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        int count = employeeService.deleteById(id);
        if (count == 0) {
            return Result.error();
        }
        return Result.success();
    }

    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Long> ids) {
        employeeService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(Employee employee) {
        List<Employee> list = employeeService.selectAll(employee);
        for (Employee e : list) {
            Object result = deptClient.selectById(e.getDeptId()).getData();
            System.out.println(result);
            e.setDeptName(result.toString().split("=")[2].split("}")[0]);
        }
        return Result.success(list);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable("id") Long id) {
        Employee employee = employeeService.selectById(id);
        return Result.success(employee);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(Employee employee,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Employee> pageInfo = employeeService.selectPage(employee, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    @GetMapping("/export")
    public Result export(HttpServletResponse response) throws Exception {
        System.out.println("导出");
        // 获取所有员工信息
        List<Employee> employeeList = employeeService.selectAll(null);

        JSONObject jsonObject = JSONUtil.parseObj(deptClient.selectAll());
        Object data = jsonObject.get("data");
        List<Dept> deptList = JSONUtil.toList(data.toString(), Dept.class);

        for (Employee employee : employeeList){
            for (Dept dept : deptList){
                if (dept.getId().equals(employee.getDeptId())){
                    employee.setDeptName(dept.getName());
                }
            }
        }

        // 创建ExcelWriter对象，用于写入Excel文件
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 设置Excel表格列名与字段名的别名映射
        writer.addHeaderAlias("username", "账号");
        writer.addHeaderAlias("name", "名称");
        writer.addHeaderAlias("sex", "性别");
        writer.addHeaderAlias("no", "工号");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("description", "个人介绍");
        writer.addHeaderAlias("deptName", "部门");

        // 设置只使用别名映射
        writer.setOnlyAlias(true);

        // 写入员工信息到Excel
        writer.write(employeeList, true);

        // 设置响应内容类型为Excel文件格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");

        // 对文件名进行URL编码，确保文件名在不同浏览器中正确显示
        String fileName = URLEncoder.encode("员工信息", "UTF-8");

        // 设置响应头，指定文件名和文件下载方式
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 获取响应的输出流，用于传输Excel文件
        ServletOutputStream os = response.getOutputStream();

        // 将Excel数据写入到输出流中
        writer.flush(os);

        // 关闭输出流
        os.close();
        return Result.success("导出成功");
    }

    /**
     * 导入Excel数据到系统中
     * 该方法处理POST请求，用于导入员工数据
     * 它接受一个名为file的multipart文件作为输入，解析Excel文件内容，并将数据保存到数据库中
     *
     * @param file 包含员工数据的Excel文件
     * @return 导入结果，成功则返回成功结果
     * @throws Exception 如果文件读取或数据处理过程中发生错误，则抛出异常
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws Exception {
        // 获取文件输入流
        InputStream inputStream = file.getInputStream();
        // 使用工具类获取Excel读取器
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        // 为Excel中的列名添加别名，以便映射到Employee类的属性
        reader.addHeaderAlias("账号", "username");
        reader.addHeaderAlias("名称", "name");
        reader.addHeaderAlias("性别", "sex");
        reader.addHeaderAlias("工号", "no");
        reader.addHeaderAlias("年龄", "age");
        reader.addHeaderAlias("个人介绍", "description");
        reader.addHeaderAlias("部门", "deptName");

        // 读取Excel文件中的所有数据，并转换为Employee对象列表
        List<Employee> employeeList = reader.readAll(Employee.class);
        // 获取系统中所有的部门信息
//    List<Dept> deptList = deptService.selectAll(null);
        JSONObject jsonObject = JSONUtil.parseObj(deptClient.selectAll());
        Object data = jsonObject.get("data");
        List<Dept> deptList = JSONUtil.toList(data.toString(), Dept.class);

        // 遍历员工列表，为每个员工设置部门ID，并保存到数据库
        for (Employee employee : employeeList) {
            for (Dept dept : deptList) {
                if (dept.getName().equals(employee.getDeptName())) {
                    employee.setDeptId(dept.getId());
                }
            }
            employeeService.add(employee);
        }

        // 返回成功结果
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody Account account){
        System.out.println(timeout);
        Account result = employeeService.login(account);
        String token = JwtUtils.createToken(result.getId().toString(),timeout);
        result.setToken(token);
        return Result.success(result);
    }

    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account account){
        employeeService.updatePassword(account);
        return Result.success();
    }

    @PostMapping("/register")
    public Result register(@RequestBody Employee employee){
        employeeService.register(employee);
        return Result.success();
    }
}































